package com.xiaoyi.ui.activity;

import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.xiaoyi.App;
import com.avin.yi.R;
import com.bumptech.glide.Glide;
import com.xiaoyi.entity.XyData;
import com.xiaoyi.tool.AvBaseTool;
import com.xiaoyi.tool.UrlTool;
import com.xiaoyi.entity.music.EventBusBean;
import com.xiaoyi.entity.music.EventType;
import com.xiaoyi.entity.music.SeekBean;
import com.xiaoyi.tool.http.XyApi;
import com.xiaoyi.ui.view.TxtItemListDialog;
import com.xiaoyi.listener.OnMusicItemClickListener;
import com.xiaoyi.service.MusicService;
import com.ywl5320.bean.TimeBean;
import com.ywl5320.util.WlTimeUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import jp.wasabeef.glide.transformations.BlurTransformation;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;


public class MusicPlayActivity extends AppCompatActivity {
    TextView tvNowTime;
    TextView tvTotalTime;
    SeekBar seekBar;
    ImageView ivBg;
    ProgressBar pbLoad;
    ProgressBar pbMiniLoad;
    ImageView ivStatus ;
    private static final String KEY_INDEX = "indext" ;
    private List<XyData> musicList ;
    private TextView lrcView;

    public static void startInceTance(Context context ,int index){
         Intent intent = new Intent(context , MusicPlayActivity.class) ;
        intent.putExtra( KEY_INDEX ,index) ;
        context.startActivity(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_play_layout);
        if(getSupportActionBar()!=null){
            getSupportActionBar().hide();
        }


        EventBus.getDefault().register(this);
        App.playingIndex = getIntent().getIntExtra(KEY_INDEX  , 0) ;
        musicList =  App.musicList;



        ivBg = findViewById(R.id.iv_bg) ;
        Glide.with(this).load(R.mipmap.icon_gray_bg)
                .apply(bitmapTransform(new BlurTransformation(25, 3)).placeholder(R.mipmap.icon_gray_bg))
                .into(ivBg);

        initView();


        boolean running = isServiceExisted(MusicService.class.getName()) ;
        if(running){
            EventBus.getDefault().post( new EventBusBean(EventType.MUSIC_NEXT_USER,   App.playingIndex  ));
        }else{
            Intent intent = new Intent(MusicPlayActivity.this, MusicService.class);
            intent.putExtra("url",  getRealURl( App.playingIndex) );
            startService(intent);
        }


    }


    private void initView(){
        initLrc();
        tvNowTime= findViewById(R.id.tv_nowtime) ;
        tvTotalTime= findViewById(R.id.tv_totaltime) ;
        seekBar= findViewById(R.id.seek_bar) ;
        pbLoad= findViewById(R.id.pb_load) ;
        ivStatus =findViewById(R.id.iv_status) ;
        pbMiniLoad=findViewById(R.id.pb_mini_load);
        findViewById(R.id.iv_pre).setOnClickListener(onClickListener);
        findViewById(R.id.iv_status).setOnClickListener(onClickListener);
        findViewById(R.id.iv_next).setOnClickListener(onClickListener);
        seekBar.setOnSeekBarChangeListener( onSeekBarChangeListener );
        findViewById(R.id.showDialog).setOnClickListener(onClickListener);

    }


    private void initLrc(){
        lrcView =  findViewById(R.id.lrcView);
    }



    private void loadLrc(int index ){
        XyApi.getInstance(this).loadLrcByUrl( new SingleObserver<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onSuccess(String result) {
                lrcView.setText(result);

            }

            @Override
            public void onError(Throwable e) {

            }
        } ,getLrcUrl(index) );
    }


    public  String getRealURl(int index  ) {

       if(index>=musicList.size()){
            return "错误地址" ;
        }
        String  url =UrlTool.getDataLastUrl( musicList.get(index) ) ;
        AvBaseTool.e("1---->"+url);
        return   url;
    }

    public  String getLrcUrl(int index  ) {
        String url =UrlTool.getLrcUrl( musicList.get(index) ) ;
        AvBaseTool.e("2---->"+url);
        return  url ;
    }






    private boolean pause = false ;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.iv_pre:
                    if(App.playingIndex==0){
                        showToast("已经是第一首");
                        return;
                    }
                    EventBus.getDefault().post( new EventBusBean(EventType.MUSIC_NEXT_USER,   --App.playingIndex ));
                    break;
                case R.id.iv_status:
                    pause = !pause;
                    EventBus.getDefault().post( new EventBusBean(EventType.MUSIC_PAUSE_RESUME,   pause));
                    break;
                case R.id.iv_next:
                    playerNext();

                    break;
                case R.id.showDialog:
                    showList();
                    break;
                default:
                    break;
            }

        }
    };


    private void playerNext(){
        if(App.playingIndex>=musicList.size()-1){
            showToast("已经是最后一首");
            return;
        }
        EventBus.getDefault().post( new EventBusBean(EventType.MUSIC_NEXT_USER,     ++App.playingIndex  ));
    }

    TxtItemListDialog musicListDialog ;
    public void showList( )
    {
        if(musicListDialog == null)
        {
            musicListDialog = new TxtItemListDialog(  this , getStringList(musicList) );
            musicListDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    musicListDialog = null;
                }
            });

            musicListDialog.setOnItemClickListener(new OnMusicItemClickListener() {
                @Override
                public void onItemClick(int  postion  ) {
                    App.playingIndex =postion ;
                    EventBus.getDefault().post( new EventBusBean(EventType.MUSIC_NEXT_USER,   postion  ));

                }
            });
        }else{
            musicListDialog.setDatas( getStringList(musicList) );
        }
        musicListDialog.setSelectedItemColor(App.playingIndex);
        musicListDialog.show();
    }

    private List<String> getStringList( List<XyData> list){
        List<String> reslut =new ArrayList<>() ;
        for(XyData bean : list){
            reslut.add(bean.getmName()) ;
        }
        return  reslut ;
    }


    EventBusBean eventSeekBean  ;
    SeekBean seekBean ;
    private int position = 0;
    TimeBean  timeBean  =new TimeBean();
    private SeekBar.OnSeekBarChangeListener  onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            position = timeBean.getTotalSecs() * progress / 100;
            tvNowTime.setText(WlTimeUtil.secdsToDateFormat(position, timeBean.getTotalSecs()));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            if(seekBean == null)   {
                seekBean = new SeekBean();
            }
            seekBean.setPosition(position);
            seekBean.setSeekingfinished(false);
            seekBean.setShowTime(false);

            if(eventSeekBean == null) {
                eventSeekBean = new EventBusBean(EventType.MUSIC_SEEK_TIME, seekBean);
            }
            else {

                eventSeekBean.setType(EventType.MUSIC_SEEK_TIME);
                eventSeekBean.setObject(seekBean);
            }
            EventBus.getDefault().post(eventSeekBean);
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            seekFinished(position) ;
        }
    } ;


    private void seekFinished(int position){
//        Log.e("55555555" ,"播放进度：" +  timeBean.getCurrSecs()  +"   "+ timeBean.getTotalSecs()  +"   "+position) ;
        if(seekBean == null)   {
            seekBean = new SeekBean();
        }
        seekBean.setPosition(position);
        seekBean.setSeekingfinished(true);
        seekBean.setShowTime(true);

        if(eventSeekBean == null) {
            eventSeekBean = new EventBusBean(EventType.MUSIC_SEEK_TIME, seekBean);
        }

        eventSeekBean.setType(EventType.MUSIC_SEEK_TIME);
        eventSeekBean.setObject(seekBean);

        EventBus.getDefault().post(eventSeekBean);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void showToast(String msg)
    {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }


    /**
     * 接收回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventMsg(final EventBusBean messBean) {
        if(messBean.getType() == EventType.MUSIC_TIME_INFO)
        {
            //时间信息
            //showToast("播放中："  );
            // 这样会浪费内存 ，要增加一个开始播放的回调才行
            ivStatus.setImageResource(R.drawable.pause_selector);
            timeBean = (TimeBean) messBean.getObject();
            if(timeBean != null)
            {
                if(timeBean.getTotalSecs() <= 0)
                {
                    if(seekBar.getVisibility() == View.VISIBLE)
                    {
                        seekBar.setVisibility(View.GONE);
                        tvTotalTime.setVisibility(View.GONE);
                    }
                    tvNowTime.setText(WlTimeUtil.secdsToDateFormat(timeBean.getCurrSecs(), timeBean.getTotalSecs()));
                }
                else
                {
                    if(seekBar.getVisibility() == View.GONE)
                    {
                        seekBar.setVisibility(View.VISIBLE);
                        tvTotalTime.setVisibility(View.VISIBLE);
                    }
                    tvTotalTime.setText(WlTimeUtil.secdsToDateFormat(timeBean.getTotalSecs(), timeBean.getTotalSecs()));
                    tvNowTime.setText(WlTimeUtil.secdsToDateFormat(timeBean.getCurrSecs(), timeBean.getTotalSecs()));

                    /// Log.e("111111" ,"播放进度：" +  timeBean.getCurrSecs()  +"   "+ timeBean.getTotalSecs() ) ;
                    /*lrcView.updateTime( timeBean.getCurrSecs() *1000 );*/
                    int progress =   timeBean != null && timeBean.getTotalSecs() > 0 ?  timeBean.getCurrSecs() * 100 / timeBean.getTotalSecs() : 0;
                    seekBar.setProgress(progress);
                }
            }

        }
        else if(messBean.getType() == EventType.MUSIC_ERROR)  {
            String errormsg = (String) messBean.getObject();
            Log.e("111111" ,"播放出错：" + errormsg) ;
        }
        else if(messBean.getType() == EventType.MUSIC_LOADLRC)  {
            int index = (int) messBean.getObject();
            loadLrc(index);

        }

        else if(messBean.getType() == EventType.MUSIC_LOAD)
        {
            boolean load = (boolean) messBean.getObject();
            if(load){
                pbMiniLoad.setVisibility(View.VISIBLE);
            }else{
                pbMiniLoad.setVisibility(View.GONE);
            }

        }
        else if(messBean.getType() == EventType.MUSIC_COMPLETE)
        {
            ivStatus.setImageResource(R.drawable.play_selector);
//            playerNext();
            Log.e("111111" ,"播放完成" ) ;
        }
        else if(messBean.getType() == EventType.MUSIC_PAUSE_RESUME_RESULT)
        {
            boolean pause = (boolean) messBean.getObject();

            if(pause){
                ivStatus.setImageResource(R.drawable.play_selector);
            }else{
                ivStatus.setImageResource(R.drawable.pause_selector);

            }
        }
    }



    /**
     * 判断service是否已经运行
     */

    public boolean isServiceExisted(String className) {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = am.getRunningServices(Integer.MAX_VALUE);
        if (!(serviceList.size() > 0)) {
            return false;
        }

        int myUid = android.os.Process.myUid();
        for (ActivityManager.RunningServiceInfo runningServiceInfo : serviceList) {
            if (runningServiceInfo.uid == myUid && runningServiceInfo.service.getClassName().equals(className)) {
                return true;
            }
        }
        return false;
    }


}


